﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Process;
using Process.Entities;
using Process.BLL;
using System.Text.RegularExpressions;
using KZ.Utilities;

namespace Provider
{
    public partial class Transaction : System.Web.UI.Page
    {
        Regex regex = new Regex(@"(.*)(\?op\=)(.*)");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadPartner();
                LoadTransaction();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadTransaction();
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            List<TransactionENT> transList = new List<TransactionENT>();
            CheckBox chk = new CheckBox();
            foreach (GridViewRow row in dtgTransaction.Rows)
            {
                chk = row.FindControl("chkSelect") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    string transID = Utility.StringParse(dtgTransaction.DataKeys[row.RowIndex].Value);
                    HiddenField hidden = row.FindControl("hidPartnerID") as HiddenField;

                    transList.Add(new TransactionENT
                    {
                        TransID = transID,
                        PartnerID = hidden.Value,
                    });
                }
            }

            int numberOfPartner = transList.GroupBy(t => t.PartnerID).Count();
            for (int i = 0; i < numberOfPartner; i++)
            {
                List<TransactionENT> tempList = new List<TransactionENT>(transList.
                    Where(t => t.PartnerID == transList[0].PartnerID));
                transList.RemoveAll(t => t.PartnerID == tempList[0].PartnerID);

                PartnerENT partner = PartnerBLL.GetPartnerByID(tempList[0].PartnerID);
                UpdateTransStatus(partner.WS3, tempList, TransStatus.Success);
            }

            LoadTransaction();
        }

        protected void btnRefuse_Click(object sender, EventArgs e)
        {
            List<TransactionENT> transList = new List<TransactionENT>();
            CheckBox chk = new CheckBox();
            foreach (GridViewRow row in dtgTransaction.Rows)
            {
                chk = row.FindControl("chkSelect") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    string transID = Utility.StringParse(dtgTransaction.DataKeys[row.RowIndex].Value);
                    HiddenField hidden = row.FindControl("hidPartnerID") as HiddenField;

                    transList.Add(new TransactionENT
                    {
                        TransID = transID,
                        PartnerID = hidden.Value,
                    });
                }
            }

            int numberOfPartner = transList.GroupBy(t => t.PartnerID).Count();
            for (int i = 0; i < numberOfPartner; i++)
            {
                List<TransactionENT> tempList = new List<TransactionENT>(transList.
                    Where(t => t.PartnerID == transList[0].PartnerID));
                transList.RemoveAll(t => t.PartnerID == tempList[0].PartnerID);

                PartnerENT partner = PartnerBLL.GetPartnerByID(tempList[0].PartnerID);
                UpdateTransStatus(partner.WS3, tempList, TransStatus.Failure);
            }

            LoadTransaction();
        }

        protected void btnCheckQuantity_Click(object sender, EventArgs e)
        {
            TransactionENT trans = new TransactionENT();
            CheckBox chk = new CheckBox();
            foreach (GridViewRow row in dtgTransaction.Rows)
            {
                chk = row.FindControl("chkSelect") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    string transID = Utility.StringParse(dtgTransaction.DataKeys[row.RowIndex].Value);
                    HiddenField hidden = row.FindControl("hidPartnerID") as HiddenField;

                    trans = new TransactionENT
                    {
                        TransID = transID,
                        PartnerID = hidden.Value,
                    };

                    break;
                }
            }

            if (!String.IsNullOrEmpty(trans.TransID))
            {
                Response.Redirect("ProductQuantity.aspx?t=" + trans.TransID + "&p=" + trans.PartnerID);
            }
        }

        private void LoadPartner()
        {
            ddlPartner.DataSource = PartnerBLL.GetPartnerListForCMB();
            ddlPartner.DataBind();
        }

        private void LoadTransaction()
        {
            TransStatus status = TransStatus.Draft;
            string type = Request.QueryString["t"];
            if (type == "d") { status = TransStatus.Draft; }
            else if (type == "s") { status = TransStatus.Success; }

            List<TransactionENT> transList = TransactionBLL.GetTransactionList(ddlPartner.SelectedValue, status);
            dtgTransaction.DataSource = transList;
            dtgTransaction.DataBind();

            btnAccept.Visible = transList.Count > 0 && type == "d";
            btnRefuse.Visible = transList.Count > 0 && type == "d";
            btnCheckQuantity.Visible = transList.Count > 0 && type == "s";
        }

        private void UpdateTransStatus(string wsLink, List<TransactionENT> transList, TransStatus status)
        {
            string ws = regex.Replace(wsLink, "$1");
            if (!ws.EndsWith("?wsdl")) { ws += "?wsdl"; }
            WebServiceInvoker invoker = new WebServiceInvoker(new Uri(ws));

            string methodName = regex.Replace(wsLink, "$3");
            TransactionBLL transBLL = new TransactionBLL();
            bool hasError = false;
            foreach (TransactionENT trans in transList)
            {
                object[] obj = { Global.PartnerSID, trans.TransID };
                string result = invoker.InvokeMethod<string>(invoker.AvailableServices[0], methodName, obj);
                if (result == "0")
                {
                    transBLL.UpdateTransactionStatus(trans.TransID, status);
                }
                else
                {
                    hasError = true;
                }
            }

            if (hasError)
            {
                lblMessage.Text = "Một số giao dịch thao tác không thành công.";
                message.Attributes.Add("class", "notification error png_bg message");
            }
            else
            {
                lblMessage.Text = "Giao dịch thao tác thành công.";
                message.Attributes.Add("class", "notification success png_bg message");
            }
            message.Style["display"] = "block";
        }
    }
}